#include "HY.h"
#include "stdio.h"


uint8_t buf_tmp;
uint16_t distance_cm;


void init_HY_GPIO()
{
   GPIO_InitTypeDef GPIO_Initure;
	
	__HAL_RCC_TIM3_CLK_ENABLE();
	__HAL_RCC_GPIOB_CLK_ENABLE(); 
GPIO_Initure.Pin=GPIO_PIN_6; 
GPIO_Initure.Mode=GPIO_MODE_OUTPUT_PP; 
GPIO_Initure.Pull=GPIO_PULLDOWN;
GPIO_Initure.Speed=GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOB,&GPIO_Initure);

GPIO_Initure.Pin=GPIO_PIN_7;
GPIO_Initure.Mode=GPIO_MODE_INPUT; 
GPIO_Initure.Pull=GPIO_PULLDOWN;
HAL_GPIO_Init(GPIOB,&GPIO_Initure);

}


void delay_us(uint32_t us)
{
  uint32_t delay = (HAL_RCC_GetHCLKFreq()/4000000*us);
	while(delay--)
	{
			;
	}

}
void func_trig_supersonic()
{
	HAL_GPIO_WritePin(GPIOB,GPIO_PIN_6,GPIO_PIN_SET);
	delay_us(12);
	HAL_GPIO_WritePin(GPIOB,GPIO_PIN_6,GPIO_PIN_RESET);
}
 

uint8_t func_get_supersonic_echo_signal(uint16_t *distance_cm)
{
	uint16_t counter_high;
	uint16_t timeout;
	
	func_trig_supersonic();
	for(;;)
	{
		delay_us(1);
		if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_7) == GPIO_PIN_SET)
		{
			counter_high ++;
			if(counter_high > 13235)
			{
				return 2;
			}
		}
		else
		{
			if(counter_high > 1)
			{
				*distance_cm = ((counter_high)*10)/294;
				return 0;
			}
			timeout++;
		}
		if(timeout > 13235)
		{
			return 2;
		}
	}
}


uint8_t measure()//
{
				if(func_get_supersonic_echo_signal(&distance_cm) == 0)
		{
			buf_tmp = (uint8_t)distance_cm;
			distance_cm = 0;
			return buf_tmp;
		}
}


